<template>
  <div>
    <el-input v-model="selectedItemsText" readonly placeholder="请选择..." @click="handleClick" :disabled="disabled"></el-input>
    <el-dialog v-model="showDialog" title="选择项" width="80%">
      <el-table ref="multipleTableRef" :data="items" @selection-change="handleSelectionChange" style="width: 100%">
        <el-table-column type="selection" width="55"></el-table-column>
        <el-table-column prop="nickName" label="名称"></el-table-column>
        <el-table-column prop="deptName" label="部门"></el-table-column>
      </el-table>
      <el-pagination layout="prev, pager, next" background :total="items.length" :page-size="pageSize" :current-page="currentPage" @current-change="handlePageChange" style="float: right; margin-top: 10px;" />
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="cancelSelection">取消</el-button>
          <el-button type="primary" @click="confirmSelection">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { ref, computed, watch, onMounted } from 'vue';
import { ElInput, ElDialog, ElTable, ElTableColumn, ElButton } from 'element-plus';
import { listUser } from '@/api/system/user';


export default {
  name: 'SelectionInput',
  props: {
    modelValue: Array,
    type: String,
    disabled:　Boolean
  },
  emits: ['update:modelValue', 'change'],
  components: {
    ElInput,
    ElDialog,
    ElTable,
    ElTableColumn,
    ElButton,
  },
  setup(props, context) {
    const showDialog = ref(false);
    const userIdList = ref([]);
    const items = ref([]);
    const multipleTableRef = ref(null);
    const queryParams = ref({
      pageNum: 1,
      pageSize: 10,
      userName: '',
      nickName: '',
      taskId: ''
    });
    const totalItems = ref(0); // 总条数
    const pageSize = ref(10); // 每页条目数
    const currentPage = ref(1); // 当前页码

    const selectedItemsText = computed(() => {
      if (!Array.isArray(items.value) || !Array.isArray(userIdList.value)) {
        return '';
      }
      if (props.type=='workOrder') {
        return userIdList.value.map(item => item.nickName).join(',');
      } else {
        return items.value.filter(item => userIdList.value.includes(item.userId)).map(item => item.nickName).join(',');
      }
    });
    async function fetchItems() {
      let params = {
        pageNum: currentPage.value,
        pageSize: pageSize.value
      }
      try {
        listUser(params).then(data => {
          items.value = data.rows;
          // totalItems.value = data.total;
        })
      } catch (error) {
        console.error(error);
      }
    };

    // 分页改变时触发
    function handlePageChange(newPage) {
      currentPage.value = newPage;
      fetchItems();
    }

    function handleSelectionChange(selection) {
      if (props.type=='workOrder') {
        userIdList.value = selection;
        // console.log(userIdList.value, 'workOrder')
      } else {
        userIdList.value = selection.map(item => item.userId);
      }
    };
    
    function handleClick() {
      showDialog.value = true;
      nextTick(() => {
        if (userIdList.value.length > 0) {
          const selectedRows = items.value.filter(item => userIdList.value.includes(item.userId));
          selectedRows.forEach(row => {
            multipleTableRef.value.toggleRowSelection(row, true);
          });
        }
      });
    };
    // 取消
    function cancelSelection() {
      if (multipleTableRef.value) {
        if (props.modelValue && props.modelValue.length > 0) {
          // 如果之前有选中数据，恢复到之前的选中状态
          const previousSelectedRows = items.value.filter(item =>
            props.type === 'workOrder'
              ? props.modelValue.includes(item)
              : props.modelValue.includes(item.userId)
          );
          items.value.forEach(row => {
            multipleTableRef.value.toggleRowSelection(row, false);
          });
          previousSelectedRows.forEach(row => {
            multipleTableRef.value.toggleRowSelection(row, true);
          });
        } else {
          // 如果之前没有选中数据，清空所有选中
          multipleTableRef.value.clearSelection();
        }
      }
      showDialog.value = false;
    };
    // 确定
    function confirmSelection() {
      context.emit('update: ', userIdList.value);
      context.emit('change', userIdList.value);
      // console.log(userIdList.value, 'confirmSelection')
      showDialog.value = false;
    };

    onMounted(() => {
      if (props.modelValue && props.modelValue.length > 0) {
        userIdList.value = props.modelValue;
      }
      fetchItems();
    });

    watch(() => props.modelValue, (newVal) => {
      if (JSON.stringify(newVal) !== JSON.stringify(userIdList.value)) {
        userIdList.value = newVal;
      }
    });

    return {
      showDialog,
      userIdList,
      items,
      selectedItemsText,
      multipleTableRef,
      handleSelectionChange,
      handleClick,
      cancelSelection,
      confirmSelection,
      handlePageChange,
    };
  },
};
</script>